package com.jinrustar.weimaqi

import com.alibaba.fastjson.JSON
import com.jinrustar.weimaqi.action.CoinStatusReqAction
import com.jinrustar.weimaqi.action.DeviceStatusReqAction
import com.jinrustar.weimaqi.action.OrderStatusReqAction
import com.jinrustar.weimaqi.action.PayoutReqAction
import com.jinrustar.weimaqi.app.Constant
import com.jinrustar.weimaqi.util.AppUtil
import com.jinrustar.weimaqi.util.HttpUtil
import org.apache.commons.codec.digest.DigestUtils
import java.util.*


/**
 * Created by liduanwei on 2017/10/26 0026. liduanwei1988@gmail.com
 */
object WeimaqiApi {
    private val uri = Constant.DOMAIN + Constant.ACTION_PATH


    fun payout(deviceName: String, coinCount: Int = 0, orderId: String): String {
        val allFieldsWithValueMap = PayoutReqAction(deviceName, orderId, coinCount).getAllFieldsWithValue()
        return httpPost(allFieldsWithValueMap)
    }


    fun deviceStatus(deviceName: String): String {
        val allFieldsWithValueMap = DeviceStatusReqAction(deviceName).getAllFieldsWithValue()
        return httpPost(allFieldsWithValueMap)
    }


    fun orderStatus(orderId: String): String {
        val allFieldsWithValueMap = OrderStatusReqAction(orderId).getAllFieldsWithValue()
        return httpPost(allFieldsWithValueMap)
    }

    fun coinStatus(deviceName: String, status: String, startTime: String, endTime: String, pageNo: Int, pageSize: Int): String {
        val allFieldsWithValueMap = CoinStatusReqAction(deviceName, status, startTime, endTime, pageNo, pageSize).getAllFieldsWithValue()
        return httpPost(allFieldsWithValueMap)
    }

    fun payoutNotifyResp(result: Int, err_msg: String): String {
        var resultMap = TreeMap<String, Any>()
        resultMap.put("result", result)

        resultMap.put("err_msg", err_msg)
        val paramsStr = AppUtil.concatWithApiKey(resultMap)
        resultMap.put("sign", getSign(paramsStr))
        return JSON.toJSONString(resultMap)
    }


    fun getSign(str: String): String {
        return DigestUtils.md5Hex(str.toByteArray()).toUpperCase()
    }

    private fun httpPost(paramsMap: TreeMap<String, Any>): String {
        val paramsStr = AppUtil.concatWithApiKey(paramsMap)
        paramsMap.put("sign", getSign(paramsStr))
        val jsonData = JSON.toJSONString(paramsMap)
        val bytes = HttpUtil.httpPost(uri, jsonData)
        return (String(bytes))
    }
}